package com.example.mqtt.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.annotation.Router;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.integration.router.AbstractMessageRouter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;

/**
 * 消息路由：向管道投递消息时，可由消息路由根据路由规则选择投递的管道
 * All mqtt broker messages will arrive here before distributing them to different channels
 *
 * @author：yu8home
 * @date：2025年7月14日 下午3:44:13
 */
@Component
@Slf4j
public class InboundMessageRouter extends AbstractMessageRouter {

    @Override
    @Router(inputChannel = "mqttInboundChannel")
    protected Collection<MessageChannel> determineTargetChannels(Message<?> message) {
        MessageHeaders headers = message.getHeaders();

        String topic = headers.get(MqttHeaders.RECEIVED_TOPIC).toString();
        if (topic.indexOf("/") > -1) {
            topic = StrUtil.subAfter(topic, "/", true);
        }
        topic = StrUtil.toCamelCase(topic) + "Channel";

        // No bean named 'currentStatus7Channel' available
        MessageChannel bean = SpringUtil.getBean(topic);
        return Collections.singleton(bean);
    }

}
